package cs2340.todolist.controller;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import cs2340.todolist.R;
import cs2340.todolist.application.ToDoListApplication;
import cs2340.todolist.controller.account_activities.LoginScreenActivity;
import cs2340.todolist.model.Location;
import cs2340.todolist.model.ToDoItem;
import cs2340.todolist.model.User;
import cs2340.todolist.model.account_management.AccountManager;
import cs2340.todolist.model.account_management.ToDoListManager;
import cs2340.todolist.model.session_management.SessionManager;
import cs2340.todolist.model.sqlite_database.ToDoItemDataSource;
import cs2340.todolist.view.MapPin;
import cs2340.todolist.view.TodoItemsView;


public class HomeScreenActivity extends MapActivity {
	
	private AccountManager accountManager;
	private SessionManager sessionManager;
	private ToDoListManager toDoListManager;
	
	/**
	 * called when the activity is first created
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_screen);

		
        
		final Button filterButton = (Button) findViewById(R.id.filter_items_button);
        filterButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//this brings up the login screen if the cancel button is pressed
				Intent filterScreenIntent = new Intent(HomeScreenActivity.this,FilterActivity.class);
				startActivity(filterScreenIntent);
			}
        });
        
        final Button logOutButton = (Button) findViewById(R.id.log_out_button);
        logOutButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				Intent goToLogin = new Intent(HomeScreenActivity.this,LoginScreenActivity.class);
				startActivity(goToLogin);
			}
        });
        
		final ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.home_screen_view_flipper);
        final Button showMapButton = (Button)findViewById(R.id.home_screen_show_map);
        showMapButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		viewFlipper.showNext();
        	}
        });
        
        
        
	}
	
	/**
	 * called whenever this activity is started
	 */
	public void onStart() {
		super.onStart();
		
		//grabs the account manager from background application
        accountManager = ((ToDoListApplication)getApplication()).getSessionManager().getAccountManager();
        accountManager.changeContext(this);
        sessionManager = ((ToDoListApplication)getApplication()).getSessionManager();
        
        //get the MapView, clear all pin markers
        final MapView map = (MapView)findViewById(R.id.how_screen_map_view);
        map.getOverlays().clear();
        map.invalidate();
        map.setBuiltInZoomControls(true);
		map.getController().setZoom(3);
        //gets the current user
		final User currentUser = accountManager.getCurrentUser();
		//creates a todolist manager for that user
		toDoListManager = new ToDoListManager(this,currentUser);
		//fetches the items for that user from the database
		toDoListManager.fetchToDoItems();
		//gets the items from the manager and puts it into an iterator
		Iterator<ToDoItem>	toDoItemsIterator = toDoListManager.getToDoListIterator(sessionManager.getCurrentFilter());
		//adds all the items to the todoitems view
		final TodoItemsView scrollableTable = (TodoItemsView)findViewById(R.id.to_do_items_view);
		List<Overlay> mapOverlays = map.getOverlays();
		MapPin mapPin = new MapPin(this);
		
		while(toDoItemsIterator.hasNext()) {
			ToDoItem item = toDoItemsIterator.next();
			scrollableTable.addToDoItemButton(item);
			//add item to the map
			GeoPoint geoPoint = item.getLocation().geocode(this);
			
			if(geoPoint != null) {
				mapPin.addOverlay(new OverlayItem(geoPoint, item.getTitle(), item.getLocation().toString()));
			}
		}
		mapOverlays.add(mapPin);
		
		
		
		final EditText addToDoItemEditText = (EditText)findViewById(R.id.home_screen_add_item_quick_edit_text);
		final LinearLayout addItemContainer = (LinearLayout)findViewById(R.id.home_screen_add_item);
		final Button addItemCancel = (Button)findViewById(R.id.home_screen_add_item_cancel_button);
		final Button addTaskButton = (Button) findViewById(R.id.add_item_button);
       
		addTaskButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				addItemContainer.setVisibility(View.VISIBLE);
			}
        });
        
		addToDoItemEditText.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View view, int keycode, KeyEvent event) {
			
				if(keycode == KeyEvent.KEYCODE_ENTER) {
					System.out.println("ADDING ITEM");
					ToDoItemDataSource dataSource = new ToDoItemDataSource(HomeScreenActivity.this);
					dataSource.open();
					dataSource.insertItem(	accountManager.getCurrentUser().getId(),  
							addToDoItemEditText.getText().toString(),
							new Location("",""), 
							0, 
							new Date(),
							0, 
							"",
							false);
					dataSource.close();
					addItemContainer.setVisibility(View.GONE);
					addToDoItemEditText.setText("");
					
					//removing current items and add them to the map
					toDoListManager = new ToDoListManager(HomeScreenActivity.this,currentUser);
					toDoListManager.fetchToDoItems();

					Log.d("adding item", "prepare refreshing view");

					
					//add the last which is the newest element from the todolist to the scrollable table and map
					Log.d("adding item", "start refreshing view");
					List<ToDoItem> items = toDoListManager.getToDoList().getToDoItems();
					final ToDoItem item = items.get(items.size()-1);
					scrollableTable.addToDoItemButton(item);
					Log.d("adding item", "add to scroll view");
					
					return true;
				}
				return false;
			}
			
		});
		
		addItemCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				addItemContainer.setVisibility(View.GONE);
				addToDoItemEditText.setText("");
			}
			
		});
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
